import router from "@/router"
import nprogress from "nprogress"
import 'nprogress/nprogress.css'
import useUserStore from "@/stores/modules/user"
import pinia from "@/stores"
import { getToken, removeToken } from "./token"
import { asyncRoutes } from "@/router/constantRoutes"
const userStore = useUserStore(pinia)
router.beforeEach(async (to, from, next) => {
    nprogress.start()
    if (getToken()) {
        //has token
        if (to.path == '/login') {
            // go login
            next({ path: '/' })
        } else {
            // dont go login
            if (userStore.name) {
                //has userinfo
                next()
            } else {
                //no userinfo
                try {
                    //token intime
                    await userStore.getUserInfo()
                    /* asyncRoutes.map((route)=>{
                        router.addRoute(route)
                    }) */
                    next({ ...to, replace: true })
                } catch {
                    //token timeout
                    next({ path: '/login' })
                }
            }
        }
    } else {
        //no token
        if (to.path == '/login') {
            next()
        } else {
            next({ path: '/login' })
        }

    }
})

router.afterEach((to, from) => {
    nprogress.done()
})
